<template>
    <div class="fund-query">
        <vxe-table
            :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
            :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
            :data="tableData"
            :key="tableKey + 'tableKey'"
            v-loading="loading"
            border
            stripe
            resizable
            :auto-resize="true"
            :sort-config="{
                defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                remote: true,
            }"
            highlight-current-row
            @sort-change="changeTableSort"
            :resizable-config="{ minWidth: '60' }"
            ref="table"
            show-header-overflow="tooltip"
            show-footer-overflow="tooltip"
            header-align="center"
        >
            <vxe-column
                v-for="item in showFieldList"
                :field="item.id"
                :title="item.content"
                :key="item.content"
                :align="getAlign(item)"
                :min-width="item.minWidth || '105px'"
                show-overflow="tooltip"
                sortable
            >
                <template slot-scope="scope">
                    <span v-if="formatParam.includes(item.id)">{{ numberFormat(scope.row[item.id], 2) || '--' }} </span>
                    <span v-else-if="'directDate' == item.id">
                        {{ dateFormat(scope.row[item.id]) || '--' }} {{ timeFormat(scope.row['directTime']) }}
                    </span>
                    <!-- <span v-else-if="'directTime' == item.id">
                        {{ timeFormat(scope.row[item.id]) || '--' }}
                    </span> -->
                    <span v-else-if="['poReDayTerm', 'poDayTerm'].includes(item.id)">
                        {{ thousandsFormat(scope[item.id]) || '--' }}
                    </span>
                    <span v-else>
                        {{ scope.row[item.id] === 0 || (scope.row[item.id] && (scope.row[item.id] + '').trim()) ? scope.row[item.id] : '--' }}
                    </span>
                </template>
            </vxe-column>
        </vxe-table>
        <risk-pagination :paging="page" @page-change="pageRet"></risk-pagination>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            :reset-no-selected-field-list="resetNoSelectedFieldList"
            table-name="TN_INSTRUCTION"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import ColumnUtil from '@/pages/risk-time/utils/column-util';
import { dateFormat, numberFormat, thousandsFormat, timeFormat } from '@/utils/tools';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({ name: 'Instruction', components: { RiskTableLayout, RiskPagination } })
export default class Instruction extends Vue {
    @Prop()
    transData: any;

    numberFormat = numberFormat;
    timeFormat = timeFormat;
    dateFormat = dateFormat;
    thousandsFormat = thousandsFormat;

    resetNoSelectedFieldList = [
        { id: 'fundCode', content: '产品序号' },
        { id: 'fundName', content: '产品名称' },
    ];

    layoutDialog: boolean = false; // 布局显示值

    showFieldList: any[] = []; // 展示字段

    selectedFieldList: any[] = []; // 已选字段

    fixedFieldList: any[] = [
        { id: 'instNo', content: '指令序号(赢和风控)', minWidth: '160px' },
        { id: 'dailyInstructionNo', content: '指令序号(恒生)', minWidth: '130px' },
    ];

    tableData: any[] = []; // 表格数据

    tableKey: number = -1; // 表格渲染key

    loading: boolean = false; // 页面加载

    private sortProp: string = 'instNo'; // 排序字段

    private sortOrder: string = 'asc'; // 排序方式

    sort: string = 'N_INST_NO ASC'; // 默认排序字段

    private page: pages = {
        currentPage: 1,
        pageSize: 10,
        total: 0,
    };

    // 需格式化字段
    formatParam = ['instAmount', 'instPrice', 'instBalance'];

    // 表格字段
    tableColumns = [
        { id: 'instNo', content: '指令序号(赢和风控)', minWidth: '160px', align: 'left' },
        { id: 'dailyInstructionNo', content: '指令序号(恒生)', minWidth: '130px', align: 'left' },
        // { id: 'batchSerialNo', content: '指令批号(恒生)', minWidth: '130px' },
        { id: 'batchNo', content: '指令批号(赢和风控)', minWidth: '160px', align: 'left' },
        { id: 'indexDailyModify', content: '指令修改序号(恒生)', minWidth: '150px', align: 'left' },
        { id: 'fundCode', content: '产品序号', align: 'left' },
        { id: 'fundName', content: '产品名称', align: 'left' },
        { id: 'fdAcCode', content: '组合编码', align: 'left' },
        { id: 'fdAcName', content: '组合名称', align: 'left' },
        { id: 'stockCode', content: '证券代码', align: 'left' },
        { id: 'stockNameSt', content: '证券名称', align: 'center' },
        { id: 'stTypeName', content: '证券类别', align: 'center' },
        { id: 'categoryName', content: '资产分类', align: 'center' },
        { id: 'issueCode', content: '发行人编码', minWidth: '120px', align: 'left' },
        { id: 'issueName', content: '发行人名称', minWidth: '120px', align: 'left' },
        { id: 'investType', content: '投资类型', align: 'center' },
        { id: 'realDirection', content: '委托方向', align: 'center' },
        { id: 'instAmount', content: '指令数量' },
        { id: 'instPrice', content: '指令价格' },
        { id: 'instBalance', content: '指令金额' },
        { id: 'orderPriceType', content: '价格模式', align: 'center' },
        { id: 'businClass', content: '业务类型', align: 'center' },
        { id: 'clearSpeed', content: '清算速度' },
        { id: 'poDayTerm', content: '存款期限(天)', minWidth: '120px' },
        { id: 'poReDayTerm', content: '存款剩余期限(天)', minWidth: '130px' },
        { id: 'advanceType', content: '提前支限限制', minWidth: '120px', align: 'center' },
        { id: 'opponentCode', content: '交易对手编码', minWidth: '120px', align: 'left' },
        { id: 'opponentName', content: '交易对手名称', minWidth: '120px', align: 'left' },
        { id: 'bankCode', content: '银行总行编码', minWidth: '120px', align: 'left' },
        { id: 'bankNameSt', content: '银行总行名称', minWidth: '120px', align: 'left' },
        { id: 'instStatus', content: '指令状态', align: 'center' },
        { id: 'dealExecuteStatus', content: '成交完成状态', minWidth: '120px', align: 'center' },
        { id: 'sourceType', content: '数据来源类型', align: 'center' },
        { id: 'directDate', content: '下达日期', align: 'center', minWidth: '180px' },
        // { id: 'directTime', content: '下达时间', align: 'center' },
        { id: 'direactUser', content: '指令下达人', align: 'left' },
    ];

    // 排序字段
    sortableObj = {
        instNo: 'N_INST_NO',
        batchNo: 'N_BATCH_NO',
        dailyInstructionNo: 'N_DAILY_INSTRUCTION_NO',
        indexDailyModify: 'N_INDEX_DAILY_MODIFY',
        // batchSerialNo: 'L_BATCH_SERIAL_NO',
        fundCode: 'C_FUND_CODE',
        fundName: 'C_FUND_NAME',
        fdAcCode: "TO_NUMBER(REGEXP_REPLACE(C_FD_AC_CODE, '[^0-9]', ''))",
        fdAcName: 'C_FD_AC_NAME',
        stockCode: 'C_STOCK_CODE',
        stockNameSt: 'C_STOCK_NAME_ST',
        stTypeName: 'C_ST_TYPE_NAME',
        categoryName: 'C_CATEGORY_NAME',
        issueCode: 'C_ISSUE_CODE',
        issueName: 'C_ISSUE_NAME',
        investType: 'C_INVEST_TYPE',
        realDirection: 'C_REAL_DIRECTION',
        instAmount: 'N_INST_AMOUNT',
        instPrice: 'N_INST_PRICE',
        instBalance: 'N_INST_BALANCE',
        orderPriceType: 'C_ORDER_PRICE_TYPE',
        businClass: 'C_BUSIN_CLASS', // 业务类型
        clearSpeed: 'C_CLEAR_SPEED',
        poDayTerm: 'N_PO_DAY_TERM',
        poReDayTerm: 'N_PO_RE_DAY_TERM',
        advanceType: 'C_ADVANCE_TYPE',
        opponentCode: 'C_OPPONENT_CODE',
        opponentName: 'C_OPPONENT_NAME',
        bankCode: 'C_BANK_CODE',
        bankNameSt: 'C_BANK_NAME_ST',
        instStatus: 'C_INST_STATUS',
        dealExecuteStatus: 'C_DEAL_EXECUTE_STATUS', // 成交完成状态
        sourceType: 'C_SOURCE_TYPE',
        directDate: 'CONCAT(D_DIRECT_DATE,D_DIRECT_TIME)',
        directTime: 'D_DIRECT_TIME',
        direactUser: 'C_DIREACT_USER',
    };
    isFirst: boolean = true;
    currentRecord: any = {};
    @Watch('transData', { immediate: true, deep: true })
    async handleTab(nowVal, oldVal) {
        if (nowVal['activeTab'] == 'Instruction') {
            this.layoutDialog = nowVal.detailLayoutDialog;
            if (this.isFirst) {
                await this.queryLayout();
                this.getInstructionTableData();
                this.isFirst = false;
            } else if (
                !oldVal ||
                JSON.stringify(oldVal.clickRow) !== JSON.stringify(nowVal.clickRow) ||
                JSON.stringify(nowVal.clickRow) !== JSON.stringify(this.currentRecord)
            ) {
                this.currentRecord = JSON.parse(JSON.stringify(nowVal.clickRow));
                !oldVal && (await this.queryLayout());
                this.getInstructionTableData();
            }
        }
    }

    @Watch('layoutDialog')
    handleLayoutDialog() {
        this.$emit('layout-handle', this.layoutDialog);
    }

    ColumnUtil = new ColumnUtil();
    mounted() {
        this.tableColumns = this.ColumnUtil.handleTableColumns(this.tableColumns, 'id');
    }

    getInstructionTableData() {
        if (JSON.stringify(this.transData.clickRow) == '{}') {
            return;
        }
        this.loading = true;
        this.$axios
            .post('/productSelect/instruction', {
                paging: this.page,
                sort: this.sort,
                productCode: this.transData.clickRow.fundCode,
                productSerialNo: this.transData.clickRow.fundId,
            })
            .then((res: any) => {
                this.tableData = res.list;
                this.page.total = res.total;
                this.loading = false;
            })
            .catch(() => {
                this.loading = false;
            });
    }

    pageRet() {
        this.getInstructionTableData();
    }

    // 分页
    pageChange(curPage: number) {
        this.page.currentPage = curPage;
        this.getInstructionTableData();
    }

    // 排序改变
    private changeTableSort(column): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        let sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        this.sort = this.sortableObj[column.property] + ' ' + sortType;
        this.pageChange(1);
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/TN_INSTRUCTION')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (!resList) {
            // 新用户初始化
            const keys = this.resetNoSelectedFieldList.map(item => item.id);
            this.showFieldList = this.tableColumns.filter(item => !keys.includes(item.id));
            const fixKeys = this.fixedFieldList.map(item => item.id);
            this.selectedFieldList = this.showFieldList.filter(item => !fixKeys.includes(item.id));
        } else {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
        }
        this.tableKey++;
    }
    getAlign(ele) {
        let obj = this.tableColumns.find(item => item.id == ele.id);
        if (['assetCode', 'assetName'].includes(ele.id)) {
            return 'left';
        }
        return (obj && obj.align) || 'right';
    }
}
</script>
<style lang="scss" scoped></style>
